/**
 * 
 */
package info.niwota.group;

import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * @author qiangli
 * 
 */
public class PlaylistActivity extends ListActivity implements
		View.OnCreateContextMenuListener {
	public static final String EXTRA_PLAYLIST = "playlist";

	private static final String PLAYLIST_TRACK_CONTENT_TYPE = "vnd.android.cursor.dir/track";


	static class PlaylistListAdapter extends SimpleCursorAdapter {
		class QueryHandler extends AsyncQueryHandler {
			QueryHandler(ContentResolver res) {
				super(res);
			}

			@Override
			protected void onQueryComplete(int token, Object cookie,
					Cursor cursor) {
				mActivity.init(cursor);
			}
		}

		private PlaylistActivity mActivity = null;
		private String mConstraint = null;
		private boolean mConstraintIsValid = false;
		private AsyncQueryHandler mQueryHandler;
		protected int mIdIdx;
		protected int mTitleIdx;

		PlaylistListAdapter(Context context, PlaylistActivity currentactivity,
				int layout, Cursor cursor, String[] from, int[] to) {
			super(context, layout, cursor, from, to);
			mActivity = currentactivity;
			mQueryHandler = new QueryHandler(context.getContentResolver());
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView tv = (TextView) view.findViewById(R.id.line1);

			String name = cursor.getString(mTitleIdx);
			tv.setText(name);

			ImageView iv = (ImageView) view.findViewById(R.id.icon);

			iv.setImageResource(R.drawable.playlist_list);

			ViewGroup.LayoutParams p = iv.getLayoutParams();
			p.width = ViewGroup.LayoutParams.WRAP_CONTENT;
			p.height = ViewGroup.LayoutParams.WRAP_CONTENT;

			iv = (ImageView) view.findViewById(R.id.play_indicator);
			iv.setVisibility(View.GONE);

			view.findViewById(R.id.line2).setVisibility(View.GONE);
		}

		@Override
		public void changeCursor(Cursor cursor) {
			if (cursor != mActivity.mPlaylistCursor) {
				mActivity.mPlaylistCursor = cursor;
				super.changeCursor(cursor);
				getColumnIndices(cursor);
			}
		}

		private void getColumnIndices(Cursor cursor) {
			if (cursor != null) {
				mTitleIdx = cursor
						.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME);
				mIdIdx = cursor
						.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID);
			}
		}

		public AsyncQueryHandler getQueryHandler() {
			return mQueryHandler;
		}

		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
			String s = constraint.toString();
			if (mConstraintIsValid
					&& ((s == null && mConstraint == null) || (s != null && s
							.equals(mConstraint)))) {
				return getCursor();
			}
			Cursor c = mActivity.getPlaylistCursor(null, s);
			mConstraint = s;
			mConstraintIsValid = true;
			return c;
		}

		public void setActivity(PlaylistActivity newactivity) {
			mActivity = newactivity;
		}
	}

	private final static int MENU_BASE = 10;

	private static final int MENU_DELETE_PLAYLIST = MENU_BASE + 1;

	private static final int MENU_SHORTCUT_PLAYLIST = MENU_BASE + 2;

	public final static int MENU_SHORTCUT = 1;

	//private static final String TAG = "PlaylistActivity";

	private PlaylistListAdapter mAdapter;

	private String[] mCols = new String[] { MediaStore.Audio.Playlists._ID,
			MediaStore.Audio.Playlists.NAME };

	private Cursor mPlaylistCursor;

	private String listname;

	private Cursor getPlaylistCursor(AsyncQueryHandler async, String name) {

		StringBuilder where = new StringBuilder();
		where.append(MediaStore.Audio.Playlists.NAME + " != ''");

		//
		String[] keywords = null;
		if (name != null) {
			where.append(" AND ");
			where.append(MediaStore.Audio.Playlists.NAME + " IN (?");
			String[] emails = ContactUtils.getEmail(this, name);
			keywords = new String[emails.length + 1];
			keywords[0] = getString(R.string.audio_db_playlist_name, name);
			for (int i = 0; i < emails.length; i++) {
				where.append(",?");
				keywords[i + 1] = getString(R.string.audio_db_playlist_name,
						emails[i]);
			}
			where.append(")");
		}

		String whereclause = where.toString();
		//
		if (async != null) {
			async.startQuery(0, null,
					MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mCols,
					whereclause, keywords, MediaStore.Audio.Playlists.NAME);
			return null;
		}
		Cursor c = null;
		c = MusicUtils.query(this,
				MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mCols,
				whereclause, keywords, MediaStore.Audio.Playlists.NAME);
		return c;
	}

	public void init(Cursor cursor) {

		mAdapter.changeCursor(cursor);

		setTitle(R.string.app_playlists);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo mi = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case MENU_DELETE_PLAYLIST:
			Uri uri = ContentUris.withAppendedId(
					MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mi.id);
			getContentResolver().delete(uri, null, null);
			Toast.makeText(this, R.string.msg_playlist_deleted,
					Toast.LENGTH_SHORT).show();
			if (mPlaylistCursor.getCount() == 0) {
				setTitle(R.string.text_no_playlists);
			}
			break;
		case MENU_SHORTCUT_PLAYLIST:
			TextView tv = (TextView) mi.targetView.findViewById(R.id.line1);
			String name = tv.getText().toString();
			createShortcut(name, mi.id);
			break;
		}
		return true;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		//
		setContentView(R.layout.playlist);
		setProgressBarIndeterminate(true);
		//
		ListView lv = getListView();
		lv.setOnCreateContextMenuListener(this);
		lv.setTextFilterEnabled(true);
		mAdapter = new PlaylistListAdapter(getApplication(), this,
				R.layout.track_list_item, null,
				new String[] { MediaStore.Audio.Playlists.NAME },
				new int[] { android.R.id.text1 });
		setListAdapter(mAdapter);
		setTitle(R.string.app_playlists);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon25);
		//
		listname = getIntent().getStringExtra(EXTRA_PLAYLIST);
		getPlaylistCursor(mAdapter.getQueryHandler(), listname);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		//disable for now
		return false;
	}

	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfoIn) {
		AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfoIn;

		if (mi.id >= 0) {
			menu.add(0, MENU_DELETE_PLAYLIST, 0, R.string.menu_delete);
			menu.add(0, MENU_SHORTCUT_PLAYLIST, 0, R.string.menu_shortcut);
		}
		mPlaylistCursor.moveToPosition(mi.position);
		menu.setHeaderTitle(mPlaylistCursor.getString(mPlaylistCursor
				.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME)));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem sc = menu.add(0, MENU_SHORTCUT, 0, R.string.menu_shortcut);
		sc.setIcon(R.drawable.menu_shortcut);
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//Log.d(TAG, "position: " + position + " pid: " + id);
		Intent intent = new Intent(Intent.ACTION_EDIT);
		intent.setDataAndType(Uri.EMPTY, PLAYLIST_TRACK_CONTENT_TYPE);
		intent.putExtra(EXTRA_PLAYLIST, Long.valueOf(id).toString());
		startActivity(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SHORTCUT:
			createShortcut();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void createShortcut() {
		String name = (listname == null ? getTitle().toString() : listname);
		Shortcuts.createPlaylistsShortcut(this, name, listname);
	}

	private void createShortcut(String name, long id) {
		Shortcuts.createPlaylistShortcut(this, name, id);
	}
}
